package com.gxa.saas.portal.service.impl;

import com.gxa.saas.core.common.JsonResult;
import com.gxa.saas.core.entity.FirstClassify;
import com.gxa.saas.core.vo.GoodsVo;
import com.gxa.saas.core.vo.HomePageBannerVo;
import com.gxa.saas.portal.mapper.GoodsHomepageMapper;
import com.gxa.saas.portal.service.GoodsHomepageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsHomepageServiceImpl  implements GoodsHomepageService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private GoodsHomepageMapper goodsHomepageMapper;

    public static final String CLASSIFY_ID="Classify:";


    @Override
    public Map goodsClassify() {
        //判断商品分类是否在redis存在
        String key = CLASSIFY_ID;
        BoundValueOperations<String, Object> boundValueOps = redisTemplate.boundValueOps(key);
        Object value = boundValueOps.get();

        JsonResult jsonResult = new JsonResult();

        if (!StringUtils.isEmpty(value)) {
            //通过OObjiecttMapperc从字符串读出对象

            jsonResult.setCode("0");
            jsonResult.setData(value);

            return jsonResult.getMap();
        }


        List<FirstClassify> firstClassifies = this.goodsHomepageMapper.selectClassify();
        Map map = new HashMap();
        map.put("code",200);
        map.put("data",firstClassifies);
        redisTemplate.opsForValue().set(CLASSIFY_ID,map,2, TimeUnit.HOURS);


        return map;


    }

    @Override
    public Map selectHotGoods() {
        Set<String> keys = redisTemplate.keys("hot_cakes" + "*");
        List list = new ArrayList();
        for (String key:keys) {
            BoundValueOperations<String, Object> boundValueOps = redisTemplate.boundValueOps(key);
            Object o = boundValueOps.get();
            list.add(o);
        }

        Map map = new HashMap();
        map.put("code",200);
        map.put("data",list);
        return map;
    }

    @Override
    public Map selectSlideshow() {
        List<HomePageBannerVo> homePageBannerVos = this.goodsHomepageMapper.selectSlideshow();
        Map map = new HashMap();
        map.put("code",200);
        map.put("data",homePageBannerVos);
        return map;
    }


}
